from django.shortcuts import render

# Create your views here.
from django.shortcuts import render

# Create your views here.
from django.db.models import Q
from rest_framework.decorators import action
from rest_framework.generics import ListAPIView
from rest_framework.pagination import PageNumberPagination
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from article.serializers import ChannelSerializer, ArticleSerializer, ArticlePublicSerializer, LabelsSerializer, \
    ArticleSerializerForList, ArticleDetailSerializer, CommentPublicSerializer, ArticleCollectSerializer, \
    SearchSerializer
from article.models import Channel, Article
from question.models import Label

class PageNum(PageNumberPagination):

    page_size = 5 # 指定每一页显示数量
    max_page_size = 10  # 最大显示页数

    def get_paginated_response(self, data):
        return Response({
            'count': self.page.paginator.count,
            'next': self.get_next_link(),
            'previous': self.get_previous_link(),
            'results': data
        })


class LabelsViewSet(ModelViewSet):
    '''标签'''
    queryset = Label.objects.all()
    serializer_class = LabelsSerializer


# 3.1 获取首页左侧栏中的频道列表
class ChannelListView(ListAPIView):
    queryset = Channel.objects.all()
    serializer_class = ChannelSerializer
    pagination_class = PageNum


class ArticleViewSet(ModelViewSet):
    queryset = Article.objects.all()
    serializer_class = ArticleSerializer
    pagination_class = PageNum
    # permission_classes = [IsAuthenticated]

    # 发布文章
    # 请求路径： article/
    # 请求方式： POST
    def create(self, request, *args, **kwargs):
        try:
            user = request.user
        except Exception as e:
            user = None

        if user is not None and user.is_authenticated:
            query_params = request.data
            query_params['user'] = user.id
            serializer = ArticlePublicSerializer(data=query_params)
            serializer.is_valid(raise_exception=True)
            article = serializer.save()

            return Response({'success': True, 'message': '文章发布成功！', 'articleid': article.id})
        else:
            return Response({'success': False, 'message': '用户未登录'}, status=400)

    # 根据频道获取文章列表
    # /article/{id}/channel/
    @action(methods=['get'], detail=True, url_path='channel')
    def get_articles_by_channel(self, request, pk):
        if pk == '-1':
            articles = self.get_queryset()
        else:
            channel = Channel.objects.get(id=pk)
            articles = self.get_queryset().filter(channel=channel)

        page = self.paginate_queryset(articles)
        serializer = ArticleSerializerForList(page, many=True)
        # return Response(serializer.data)
        return self.get_paginated_response(serializer.data)

    # 根据频道id获取文章详情信息
    def retrieve(self, request, *args, **kwargs):
        id = int(self.kwargs['pk'])
        article = Article.objects.get(pk=id)
        serializer = ArticleDetailSerializer(article)
        return Response(serializer.data)

    # 给文章发表一条评论，给评论进行评论
    @action(methods=['post'], detail=True, url_path='publish_comment')
    def public_comment(self, request, pk):
        try:
            user = request.user
        except Exception:
            user = None

        if user is not None and user.is_authenticated:
            pk = int(pk)
            data = request.data
            data['article'] = pk
            data['user'] = user.id
            serializer = CommentPublicSerializer(data=data)
            serializer.is_valid()
            serializer.save()

            return Response({'success': True, 'message': '文章评论成功！'})
        else:
            return Response({'success': False, 'message': '用户未登录'}, status=400)




    # 收藏/取消收藏文章
    # 请求路径： /article/{id}/collect/
    # 请求方式： PUT
    # 收藏或者取消收藏时用的是这同一个接口，后台会自行判断到底是收藏还是取消收藏
    @action(methods=['put'], detail=True, url_path='collect')
    def collect_article(self, request, pk):
            pk = int(pk)
            article = Article.objects.get(pk=pk)
            users = article.collected_users.all()
            user = request.user


            if user in users:
                article.collected_users.remove(user)
                return Response({'success': True, 'message': '取消收藏'})
            else:
                article.collected_users.add(user)
                return Response({'success':True, 'message': '收藏成功'})


# 3.6 根据关键字搜索文章列表
class MySearchView(ListAPIView):
    queryset = Article.objects.all()
    serializer_class = SearchSerializer
    pagination_class = PageNum

    def get_queryset(self):
        keyword = self.request.query_params.get('text')
        if keyword:
            return Article.objects.filter(Q(title__contains=keyword)|Q(content__contains=keyword))
        else:
            return Article.objects.all()